﻿using System;
using System.Configuration;
using System.IO;
using System.Web;
using System.Web.Mvc;
using ImageResizer;
using Whoever.Patterns.MVC.Filters;

namespace EditorialProyectos.Website.Controllers
{
    public class FileUploadController : Controller
    {
        [AJAXExceptionHandler]
        public ActionResult UploadImage()
        {
            if (Request.Files.Count > 0)
            {
                var file = Request.Files[0];
                try
                {
                    var filename = UploadFile(file);

                    return Json(new
                    {
                        statusCode = 200,
                        status = "Image uploaded.",
                        file = filename,
                    }, "text/html");
                }
                catch (Exception ex)
                {
                    return Json(new
                    {
                        statusCode = 500,
                        status = "Error uploading image.",
                        file = string.Empty
                    }, "text/html");
                }

            }
            else
            {
                return Json(new { statusCode = 500, status = "No image provided." }, "text/html");
            }
        }

        public ActionResult UpdateImage(string relativePath)
        {
            if (Request.Files.Count > 0)
            {
                var file = Request.Files[0];
                try
                {
                    DeleteFile(relativePath);
                    var filename = UploadFile(file);

                    return Json(new
                    {
                        statusCode = 200,
                        status = "Image uploaded.",
                        file = filename,
                    }, "text/html");
                }
                catch (Exception ex)
                {
                    return Json(new
                    {
                        statusCode = 500,
                        status = "Error uploading image.",
                        file = string.Empty
                    }, "text/html");
                }
            }
            else
            {
                return Json(new { statusCode = 500, status = "No image provided." }, "text/html");
            }
        }

        private string UploadFile(HttpPostedFileBase file)
        {
            try
            {
                var width = string.IsNullOrEmpty(ConfigurationManager.AppSettings["FileUploadResizeWidth"])
                    ? 1280
                    : int.Parse(ConfigurationManager.AppSettings["FileUploadResizeWidth"]);
                var height = string.IsNullOrEmpty(ConfigurationManager.AppSettings["FileUploadResizeHeight"])
                    ? 720
                    : int.Parse(ConfigurationManager.AppSettings["FileUploadResizeHeight"]);

                var absPath = string.IsNullOrEmpty(ConfigurationManager.AppSettings["FileUploadFolder"])
                    ? string.Format("{0}\\", Server.MapPath("."))
                    : Server.MapPath(string.Format("{0}", ConfigurationManager.AppSettings["FileUploadFolder"]));

                var fileName = string.Format("{0}{1}", Guid.NewGuid(), Path.GetExtension(file.FileName));

                var absFileAndPath = string.Format("{0}{1}", absPath, fileName);

                if (!Directory.Exists(absPath))
                    Directory.CreateDirectory(absPath);
                file.SaveAs(absFileAndPath);

                var resizeEnabled = ConfigurationManager.AppSettings["FileUploadResizeEnabled"];
                var resize = !string.IsNullOrEmpty(resizeEnabled) && resizeEnabled.ToLower() == "true";

                if (resize)
                {
                    var resizeSettings = new ResizeSettings
                    {
                        Scale = ScaleMode.DownscaleOnly,
                        Width = width,
                        Height = height,
                        Mode = FitMode.Crop
                    };

                    var b = ImageBuilder.Current.Build(absFileAndPath, resizeSettings);
                    b.Save(absFileAndPath);
                }

                var configFolder = ConfigurationManager.AppSettings["FileUploadFolder"];

                var relativePath = string.IsNullOrEmpty(configFolder) ? string.Format("../FileUpload/{0}", fileName)
                    : string.Format("{0}{1}", configFolder, fileName);

                return relativePath;
            }
            catch (Exception Ex)
            {
                return "";
            }
        }

        private bool DeleteFile(string path)
        {
            try
            {
                var absolutePath = Server.MapPath(path);
                if (System.IO.File.Exists((absolutePath)))
                {
                    System.IO.File.Delete(absolutePath);
                    return true;
                }
                return false;
            }
            catch (Exception Ex)
            {
                return false;
            }
        }
    }
}
